package com.freewater.javabase.demo.mutithread.synchronize;

public class CounterMultiThread {

    public static void main(String[] args) throws InterruptedException {
        AddThread addThread = new AddThread();
        DecThread decThread = new DecThread();

        addThread.start();
        decThread.start();

        addThread.join();
        decThread.join();

        System.out.println(Counter.count);
    }

    public static class Counter {

        public static final Object lock = new Object();

        public static int count = 0;
    }

    public static class AddThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                synchronized (Counter.lock) {
                    Counter.count = Counter.count + 1;
                }
            }
        }
    }

    public static class DecThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                synchronized (Counter.lock) {
                    Counter.count = Counter.count - 1;
                }
            }
        }
    }
}
